package com.wbhz.action;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.wbhz.entity.Employee;
import com.wbhz.entity.Role;
import com.wbhz.entity.User;
import com.wbhz.service.EmployeeService;
import com.wbhz.service.RoleService;
import com.wbhz.service.UserService;
import com.wbhz.util.BeanFactory;
import com.wbhz.util.CharacterUtil;

public class UserAction {
	private static Logger logger = Logger.getLogger(UserAction.class);
	UserService userService = null;
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	//登录代码
	public String login(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
		logger.debug("执行UserAction类的login方法");
		String resultString = "";
		//通过名称获得提交的数据
		String name = request.getParameter("userName");
		String pwd = request.getParameter("userPwd");
		String code = request.getParameter("code");// 获得输入的验证码
		Integer codeInt = Integer.parseInt(code);// parseInt
		// 设置session，用于验证
		HttpSession session = request.getSession();
		// 设置userName的session，用于main页面显示
		session.setAttribute("userName", name);
//		System.out.println("\n"+session.getAttribute("name")+"\n");
		Integer codeResult = (Integer) session.getAttribute("result");// 获得验证码正确值，Image.jsp
		System.out.println("\n codeResult: "+codeResult);
		// 验证用户名和密码
		if ("" == name) {// 用户名不可为空
			return resultString = "userNameIsNull";
		}else if (true == CharacterUtil.isSpecialChar(name)){// 用户名不可非法字符
			return resultString = "userNameIsIllegal";
		}else if ("" == pwd){// 密码不可为空
			return resultString = "pwdIsNull";
		}else if (!codeInt.equals(codeResult)) {// 检验验证码
			return resultString = "codeIsFail";
		}
		User user = new User();
		user.setUserLogin(name);
		user.setUserPwd(pwd);
		User result = userService.login(user);
		// 请求转发
		if(null!=result){ //成功
			request.getSession().setAttribute("user", result);//放置session
			resultString="success";
		}else{
			resultString="fail";
		}
		System.out.println("自定义mvc解析并处理成功");
		return resultString;
	}
	//添加
	public String insert(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException, SQLException{
		System.out.println("自定义mvc的添加用户功能");
		String resultString="";
		String from = request.getParameter("from");
		if (from.equals("user")) {
			getRSList(request, response);// 获得角色表和配置表，用于下拉框
			resultString = "toUserAdd";
		}else if (from.equals("userAdd")) {
			String userNo = request.getParameter("userNo");
			String empNo = request.getParameter("empNo");
			String empName = request.getParameter("empName");
			String status = request.getParameter("status");
			String role = request.getParameter("role");
			Employee emp = new Employee();
			emp.setEno(empNo);
			emp.setEna(empName);
			EmployeeService empService = (EmployeeService)BeanFactory.getObject("employeeService");
			List<Employee> empList = empService.getEmpListByNoAndName(emp);
			if (empList.toString() != "[]") {
				logger.debug("\n empList: "+empList);
				User user = new User();
				user.setUserLogin(userNo);
				user.setUserEmpNo(empNo);
				user.setUserStatus(status);
				user.setUserRoleId(role);
				int count = userService.insert(user);
				if(count==1){
					resultString="success";
				}else{
					resultString="fail";
				}
			}else {
				resultString="fail";
			}
		}
		return resultString;
	}
	// 删除
	public String delete(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException, SQLException{
		String resultString="";
		logger.debug("执行UserAction类的delete方法");
		String id = request.getParameter("id");
		User u = new User();
		u.setUserId(Integer.parseInt(id));
		int count = userService.delete(u);
		if (count==1) {
			getSomeMood(request, response);// 获得数据
			resultString = "success";
		}else{
			resultString="fail";
		}
		return resultString;
	}
	// 修改
	public String update(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException, SQLException{
		String resultString="";
		logger.debug("执行UserAction类的update方法");
		String from = request.getParameter("from");
		if (from.equals("user")) {
			String id = request.getParameter("id");
			List<User> uList = userService.getUserById(Integer.parseInt(id));
			request.setAttribute("uList", uList);
			resultString = "toUserEdit";
		}else if (from.equals("userEdit")) {
			String id = request.getParameter("id");
			String eNo = request.getParameter("eNo");
			String eName = request.getParameter("eName");// ~~
			String status = request.getParameter("status");
			String role = request.getParameter("role");
			User u = new User();
			u.setUserId(Integer.parseInt(id));
			u.setUserEmpNo(eNo);
			u.setUserEmpNo(eName);// ~~
			u.setUserStatus(status);
			u.setUserRoleId(role);
			int count = userService.update(u);
			if (count==1) {
				resultString = "success";
			}else{
				resultString="fail";
			}
		}
		return resultString;
	}
	// 修改密码
	public String userPwd(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
		System.out.println("自定义mvc的修改密码功能");
		String resultString = "";
		String oldPwd = request.getParameter("oldPwd");
		String newPwd = request.getParameter("newPwd");
		String chkPwd = request.getParameter("chkPwd");
		User user = (User) request.getSession().getAttribute("user");
	
		if (oldPwd.equals(user.getUserPwd()) && newPwd.equals(chkPwd)) {
			user.setUserLogin(user.getUserLogin());
			user.setUserPwd(newPwd);
			int count = userService.update(user);
			System.out.println("count: "+count);
			if(count==1){
				resultString="success";
			}else{
				resultString="fail";
			}
		}else {
			resultString="fail";
		}
		System.out.println("成功：自定义mvc修改密码");
		return resultString;
	}
	// 模糊搜索
	public String search(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException, SQLException{
		logger.debug("执行UserAction类的search方法");
		String resultString="";
		String userNo = request.getParameter("userNo");
		String status = request.getParameter("status");
		String role = request.getParameter("role");
		User u = new User();
		u.setUserLogin(userNo);
		u.setUserStatus(status);
		u.setUserRoleId(role);
		List<User> list = userService.getAllUsersByCondition(u);
		System.out.println("\n list: "+list.toString());
		request.setAttribute("some", list);
		resultString = "success";
		return resultString;
	}
	// 获得角色表和配置表，用于下拉框
	public void getRSList(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException, SQLException{
		// 获得角色表
		RoleService roleService = (RoleService)BeanFactory.getObject("roleService");
		List<Role> rList = roleService.getAllMoods();
		request.setAttribute("rList", rList);
		// 获得配置表（用户状态）
//		SysConfigService sysService = (SysConfigService)BeanFactory.getObject("sysConfigService");
//		List<SysConfig> sList = sysService.getAllThressSysConfig();
//		request.setAttribute("sList", sList);
	}
	//数据分页
	public String getSomeMood(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException, SQLException{
		logger.debug("执行UserAction类的getSomeMood方法");
		String resultString="success";
		getRSList(request, response);// 获得角色表和配置表，用于下拉框
		// TODO 员工姓名显示~~ 用Map<>
		List<User> moods=null;
		try {
			moods = userService.getAllMoods();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		List<User> fenyeMoods = null;
		//集合获得了，如何让EL表达式可以访问
		request.setAttribute("list", moods);
		String currPage=request.getParameter("currentPage");
		int size=4;
		//9条数据，显示为三页,+1是处理不满一页的情况
		int totalCount = moods.size()%size==0 ?  moods.size() /size: moods.size()/size+1;
		if(null	!= currPage){
			try {
				fenyeMoods = userService.getMoodsPerPage(Integer.parseInt(currPage), size);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			request.setAttribute("currentPage", Integer.parseInt(currPage));
		}else{
			try {
				fenyeMoods = userService.getMoodsPerPage(1, size);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			request.setAttribute("currentPage", "1");//如果是null代表当前页是第一页
		}
		request.setAttribute("some", fenyeMoods);
		request.setAttribute("totalCount",totalCount);
		request.setAttribute("total",moods.size());
		return resultString;
	}
}
